//
//  CollectionAppDelegate.m
//  Collection
//
//  Created by Home on 9/15/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "CollectionAppDelegate.h"
#import "JSON.h"

@implementation CollectionAppDelegate


@synthesize window=_window;

@synthesize navigationController=_navigationController;


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    // Add the navigation controller's view to the window and display.
    self.window.rootViewController = self.navigationController;
    self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:0.507 green:0.140 blue:0.140 alpha:1];
    [self.window makeKeyAndVisible];
	
	if (![[NSUserDefaults standardUserDefaults] valueForKey:@"Email"])
    {
		
        //check weather user exists of not
        UIDevice *myDevice = [UIDevice currentDevice];
        NSString *queryStr =[NSString stringWithFormat:@"http://webservices.dhakera.com/CheckUserExistence.aspx?ID=%@&AppName=COLLECTION",myDevice.uniqueIdentifier];
        NSLog(@"query str: %@",queryStr);
        NSString *jsonString = [self stringWithUrl:[NSURL URLWithString:[queryStr stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]]];
        NSLog(@"response>>>>>>>> %@",jsonString);
        
        SBJSON *jsonParser = [[[SBJSON alloc] init] autorelease];
        NSArray *arr = [[NSArray alloc] initWithArray:[jsonParser objectWithString:jsonString error:nil]];
        NSLog(@"dic %@",arr);
        if ([arr count]>0)
        {
            NSDictionary *refreshDic = [arr objectAtIndex:0];
            
            if ([[refreshDic valueForKey:@"Status"] isEqualToString:@"Yes"])
            {
				//set no. of email 0 if user exist
				[[NSUserDefaults standardUserDefaults] setValue:@"0" forKey:@"Email"];
            }
            else
            {
                //set no. of email 50 if user not exist
                [[NSUserDefaults standardUserDefaults] setValue:@"50" forKey:@"Email"];
            }
        }
		[arr release];
		
    }
    
    
    // remove signature
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *customerSign = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/customer.jpg"];
    NSString *driverSign = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/driver.jpg"];
    BOOL success = [fileManager removeItemAtPath:customerSign error:nil];
    if (success) 
        NSLog(@"customerSign removed");
    
    success = [fileManager removeItemAtPath:driverSign error:nil];
    
    if (success) 
        NSLog(@"driverSign removed");

	
    return YES;
}


-(NSString *)stringWithUrl:(NSURL *)url
{
    NSString *URLString = nil;
	
	@try { 
		
		NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:100];
		
		NSURLResponse *response;
		NSError *error;
		
		// Make synchronous request
		NSData *urlData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
		
		// Construct a String around the Data from the response
		URLString = [[[NSString alloc] initWithData:urlData encoding:NSASCIIStringEncoding] autorelease];
	}
	
	@catch (id e) {
		
		NSLog(@"Model stringWithUrl: %@", e);
		@throw;
	}
	
	NSAssert (URLString != nil, @"Invalid value of URLString in +[Model stringWithUrl:]");
	
	return URLString;
    
}

-(bool)stringFromStatus:(NetworkStatus)status
{
	bool internetConn;
	switch(status)
	{
		case NotReachable: 
			internetConn=NO;
			break; 
		case ReachableViaWiFi:
			internetConn=YES;
			break;
		case ReachableViaWWAN: 
            internetConn=YES;
			break; 
		default:
			internetConn=YES;
			break;
	}
	return internetConn;
}


- (void)applicationWillResignActive:(UIApplication *)application
{
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
     */
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    /*
     Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
     */
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    /*
     Called when the application is about to terminate.
     Save data if appropriate.
     See also applicationDidEnterBackground:.
     */
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *customerSign = [NSHomeDirectory() stringByAppendingPathComponent:@"customer.jpg"];
    NSString *driverSign = [NSHomeDirectory() stringByAppendingPathComponent:@"driver.jpg"];
    BOOL success = [fileManager removeItemAtPath:customerSign error:nil];
    if (success) 
        NSLog(@"customerSign removed");
    
    success = [fileManager removeItemAtPath:driverSign error:nil];
    
    if (success) 
        NSLog(@"driverSign removed");


    
}

- (void)dealloc
{
    [_window release];
    [_navigationController release];
    [super dealloc];
}

@end
